package com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.impl;

import com.alibaba.citrus.cr.common.enums.ordercenter.OrderCategoryEnum;
import com.alibaba.citrus.cr.common.enums.ordercenter.SalesOrgTypeEnum;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.CustomerCenterAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.ItemQueryAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.SalesOrgAbilityAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.ShipToPartyAbilityAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ItemGroupAbilityRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.SalesBizOrgByBuQueryRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ShipToPartyByAccurateQueryRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.CostCenterDTO;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.ItemGroupAbilityDTO;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.SalesBizOrgQueryDTO;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.ShipToPartyByAccurateQueryDTO;
import com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.OrderBizAssemble;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crb2btradecenter.enums.OrderStatus;
import com.epoch.app.crpricecenter.api.creditquery.dto.BatchQueryCreditListRequest;
import com.epoch.app.crpricecenter.api.creditquery.service.CreditQueryService;
import com.epoch.app.crpricecenter.model.dto.CreditInfoSDO;
import com.epoch.app.crpricecenter.model.dto.CreditQueryRequest;
import com.epoch.app.mnordercenter.model.dto.QueryCreditRequest;
import com.epoch.app.mnordercenter.model.dto.QueryCreditResponse;
import com.epoch.app.mnordercenter.model.dto.QueryGroupCreditRequest;
import com.epoch.app.mnordercenter.orderbaserequest.OrderBizUpdateRequest;
import com.epoch.app.mnordercenter.sdo.SapCreditSDO;
import com.epoch.app.mnordercenter.service.MnOrderCenterService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author zhangxiaorui
 * @date 2023/05/17 09:49
 */
@Service
@Order(5)
public class OrderUpdateBizAssembleOfCustomerCenter implements OrderBizAssemble<OrderBizUpdateRequest> {
    private static final Log log = Log.getLogger(OrderUpdateBizAssembleOfCustomerCenter.class);

    @Resource
    private ShipToPartyAbilityAdapter shipToPartyAbilityAdapter;
    @Resource
    private SalesOrgAbilityAdapter salesOrgAbilityAdapter;
    @Resource
    private CustomerCenterAdapter customerCenterAdapter;
    @Resource
    private CreditQueryService creditQueryService;
    @Resource
    private MnOrderCenterService mnOrderCenterService;
    @Resource
    private ItemQueryAdapter itemQueryAdapter;

    @Override
    public Map<String, Object> query(OrderBizUpdateRequest updateRequest) {
        return query(Lists.newArrayList(updateRequest));
    }

    @Override
    public Map<String, Object> query(List<OrderBizUpdateRequest> orderBizUpdateRequests) {
        Map<String, Object> result = Maps.newHashMap();
        if (CollectionUtils.isEmpty(orderBizUpdateRequests)) {
            return result;
        }
        // 是否校验信贷
        Boolean checkCredit = orderBizUpdateRequests.get(0).getCheckCredit();
        // F1-B-b场景下是否校验B信贷
        Boolean checkCreditB = orderBizUpdateRequests.get(0).getCheckCreditB();

        // 客户送达方
        try {
            Map<String, ShipToPartyByAccurateQueryDTO> shipToPartyMap = queryShipToPartyByAccurate(orderBizUpdateRequests, queryScItemGroupMap());
            log.info("OrderUpdateBizAssembleOfCustomerCenter#query shipToPartyMap: {}", shipToPartyMap);
            result.put(SHIP_TO_PARTY, shipToPartyMap);
        } catch (Exception e) {
            log.error("OrderUpdateBizAssembleOfCustomerCenter#query queryShipToPartyByAccurate error: {}", e);
        }

        // 客户售达方
        // Map<String, SoldToPartyByAccurateQueryDTO> soldToPartyByAccurateQueryResponseMap = querySoldToPartyByAccurate(orderBizUpdateRequests);
        //log.info("OrderUpdateBizAssembleOfCustomerCenter#query soldToPartyByAccurateQueryResponseMap: {}", soldToPartyByAccurateQueryResponseMap);

        // 业务渠道、销售组织、组织部门 等架构查询
        // Map<String, SalesBizOrgQueryDTO> salesOrgByCodeMap = findSalesOrgByCodeList(orderBizUpdateRequests);
        //log.info("OrderUpdateBizAssembleOfCustomerCenter#query salesOrgByCodeMap: {}", salesOrgByCodeMap);

        // 成本中心
        try {
            Map<String, String> costCenterNameMap = queryCostCenterByCodeList(orderBizUpdateRequests);
            result.put(COST_CENTER, costCenterNameMap);
        } catch (Exception e) {
            log.error("OrderUpdateBizAssembleOfCustomerCenter#query queryCostCenterByCodeList error: {}", e);
        }

        // 销售组织、组织部门 等架构查询
        try {
            Map<String, SalesBizOrgQueryDTO> salesOrgByCodeMap = querySalesOrgByCodeList(orderBizUpdateRequests);
            result.put(SALES_ORGANIZATION, salesOrgByCodeMap);
        } catch (Exception e) {
            log.error("OrderUpdateBizAssembleOfCustomerCenter#query querySalesOrgByCodeList error: {}", e);
        }

        // 信贷数据，仅待提交（新增、删除、修改数量），才需要信贷校验
        try {
            if (checkCredit || checkCreditB) {
                Map<String, Long> creditMap = queryCreditList(orderBizUpdateRequests);
                result.put(CREDIT_INFO, creditMap);
            }
        } catch (Exception e) {
            log.error("OrderUpdateBizAssembleOfCustomerCenter#query queryCreditList error: {}", e);
        }

        log.info("修改订单商业能力客户中心数据组装结果 result={}", JSON.toJSONString(result));
        return result;
    }

    @Override
    public Result<String> assemble(Map<String, Object> queryResponseMap, OrderBizUpdateRequest orderBizUpdateRequest) {
        // 客户送达方
        Map<String, ShipToPartyByAccurateQueryDTO> shipToPartyMap = getBizInfoMap(queryResponseMap, SHIP_TO_PARTY, ShipToPartyByAccurateQueryDTO.class);
        // 成本中心
        Map<String, String> costCenterNameMap = getBizInfoMap(queryResponseMap, COST_CENTER, String.class);
        if (shipToPartyMap.isEmpty()) {
            // 修改接口无需校验送达方等信息，直接返回
//            return Result.success(null);
            return Result.fail(orderBizUpdateRequest.getSalesOrderNo(), "OC-01-001-01-16-034", "送达方编码/名称不存在");
        }
        // 客户送达方
        if (StringUtil.isBlank(orderBizUpdateRequest.getShipToPartyCode())) {
            return Result.success(null);
        }
        ShipToPartyByAccurateQueryDTO shipToParty = shipToPartyMap.get(orderBizUpdateRequest.getShipToPartyCode());
        if (Objects.isNull(shipToParty)) {
            return Result.fail(orderBizUpdateRequest.getSalesOrderNo(), "OC-01-001-01-16-034", "送达方编码/名称不存在");
        }
        orderBizUpdateRequest.setShipToPartyCode(shipToParty.getShipToPartyCode());
        orderBizUpdateRequest.setShipToPartyName(shipToParty.getShipToPartyName());

        // 信贷校验
        if (OrderStatus.BEFORE_SUBMIT.getCode().intValue() == orderBizUpdateRequest.getStatus().intValue()) {
            if (orderBizUpdateRequest.getCheckCreditB()
                    && (!isGroupCreditMoneyEnough(orderBizUpdateRequest, getBizInfoMap(queryResponseMap, CREDIT_INFO, Long.class)))) {
                    // 信贷不足
                    return Result.fail(orderBizUpdateRequest.getSalesOrderNo(), "OC-01-001-01-16-042", "SAP信贷额度查询额度不够");
            }

            if (orderBizUpdateRequest.getCheckCredit()
                    && (!isCreditMoneyEnough(orderBizUpdateRequest, getBizInfoMap(queryResponseMap, CREDIT_INFO, Long.class)))) {
                    // 信贷不足
                    return Result.fail(orderBizUpdateRequest.getSalesOrderNo(), "OC-01-001-01-16-042", "SAP信贷额度查询额度不够");
            }
        }
        // 成本中心
        if (!StringUtils.isBlank(orderBizUpdateRequest.getCostCenterCode()) && !costCenterNameMap.containsKey(orderBizUpdateRequest.getCostCenterCode())) {
            return Result.fail(orderBizUpdateRequest.getSalesOrderNo(), "OC-01-001-01-16-029", "成本中心编码不存在");
        }
        orderBizUpdateRequest.setCostCenterName(costCenterNameMap.get(orderBizUpdateRequest.getCostCenterCode()));

        return Result.success(null);
    }

    private Map<String, ShipToPartyByAccurateQueryDTO> queryShipToPartyByAccurate(List<OrderBizUpdateRequest> salesOrderBizorderBizUpdateRequests, Map<String, ItemGroupAbilityDTO> scItemGroupListQueryMap) {
        List<ShipToPartyByAccurateQueryRequest> requests = Lists.newArrayList();
        for (OrderBizUpdateRequest orderBizUpdateRequest : salesOrderBizorderBizUpdateRequests) {
            if (!scItemGroupListQueryMap.containsKey(orderBizUpdateRequest.getProductGroupCode())) {
                // 产品组不存在时，不组装入参查询送达方信息，防止接口报错所有数据都无法拿到
                continue;
            }
            ShipToPartyByAccurateQueryRequest queryRequest = new ShipToPartyByAccurateQueryRequest();
            queryRequest.setBusinessType(orderBizUpdateRequest.getProductGroupCode());
            queryRequest.setSalesOrganizationCode(orderBizUpdateRequest.getSalesOrganizationCode());
            queryRequest.setShipToPartyCode(orderBizUpdateRequest.getShipToPartyCode());
            queryRequest.setSoldToPartyCode(orderBizUpdateRequest.getCustomerCode());
            queryRequest.setSalesChannelCode(orderBizUpdateRequest.getBusinessChannel());
            requests.add(queryRequest);
        }
        if (CollectionUtils.isEmpty(requests)) {
            return Maps.newHashMap();
        }
        log.info("requests修改接口送达方参数:{}",JSON.toJSONString(requests));
        List<ShipToPartyByAccurateQueryDTO> listResult = shipToPartyAbilityAdapter.queryShipToPartyByAccurate(requests);
        log.info("listResult修改接口结果:{}",JSON.toJSONString(listResult));
        if (CollectionUtils.isEmpty(listResult)) {
            return Maps.newHashMap();
        }

        return listResult.stream().collect(
                Collectors.toMap(ShipToPartyByAccurateQueryDTO::getShipToPartyCode, p -> p, (v1, v2) -> v1));
    }

    private Map<String, String> queryCostCenterByCodeList(List<OrderBizUpdateRequest> salesOrderBizCreateRequests) {
        List<String> costCenterCodeList = salesOrderBizCreateRequests.stream()
                .map(OrderBizUpdateRequest::getCostCenterCode)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());

        List<CostCenterDTO> costCenterDTOS = customerCenterAdapter.queryCostCenter(costCenterCodeList);

        if (CollectionUtils.isEmpty(costCenterDTOS)) {
            return Maps.newHashMap();
        }

        return costCenterDTOS.stream().collect(Collectors.toMap(CostCenterDTO::getCostCenterCode, CostCenterDTO::getCostCenterName));
    }

    /**
     * 查询信贷
     */
    private Map<String, Long> queryCreditList(List<OrderBizUpdateRequest> orderBizUpdateRequestList) {
        if (CollectionUtils.isEmpty(orderBizUpdateRequestList)) {
            return Maps.newHashMap();
        }

        OrderBizUpdateRequest orderBizUpdateRequest = orderBizUpdateRequestList.get(0);

        Map<String, Long> creditMap = Maps.newHashMap();
        if (OrderCategoryEnum.GROUP.getCode().equals(orderBizUpdateRequest.getOrderCategoryCode()) && orderBizUpdateRequest.getCheckCredit()) {
            // 集团信贷查询入参
            QueryCreditRequest groupCreditQueryRequest = new QueryCreditRequest();
            groupCreditQueryRequest.setSalesOrganizationCode(orderBizUpdateRequest.getSalesOrganizationCode());
            groupCreditQueryRequest.setDistributionChannelCode(orderBizUpdateRequest.getBusinessChannel());
            groupCreditQueryRequest.setBusinessType(orderBizUpdateRequest.getProductGroupCode());
            groupCreditQueryRequest.setSoldToPartyCode(orderBizUpdateRequest.getCustomerCode());
            creditMap.putAll(batchQueryGroupCreditList(Lists.newArrayList(groupCreditQueryRequest)));
            return creditMap;
        }

        if (OrderCategoryEnum.STOCK.getCode().equals(orderBizUpdateRequest.getOrderCategoryCode())) {
            if (orderBizUpdateRequest.getCheckCreditB()) {
                // 集团信贷查询入参
                QueryCreditRequest groupCreditQueryRequest = new QueryCreditRequest();
                // 取F-B订单上的销售组织编码
                groupCreditQueryRequest.setSalesOrganizationCode(orderBizUpdateRequest.getGroupSalesOrganizationCode());
                groupCreditQueryRequest.setDistributionChannelCode("20");
                groupCreditQueryRequest.setBusinessType(orderBizUpdateRequest.getProductGroupCode());
                // 取F-B订单上的客户编码
                groupCreditQueryRequest.setSoldToPartyCode(orderBizUpdateRequest.getGroupCustomerCode());
                creditMap.putAll(batchQueryGroupCreditList(Lists.newArrayList(groupCreditQueryRequest)));
            }
        }

        if (orderBizUpdateRequest.getCheckCredit()) {
            // 分子公司信贷查询入参
            CreditQueryRequest companyCreditQueryRequest = new CreditQueryRequest();
            companyCreditQueryRequest.setCustomerCode(orderBizUpdateRequest.getCustomerCode());
            companyCreditQueryRequest.setChannelCode(orderBizUpdateRequest.getBusinessChannel());
            companyCreditQueryRequest.setOrganizationCode(orderBizUpdateRequest.getSalesOrganizationCode());
            companyCreditQueryRequest.setItemGroupCode(orderBizUpdateRequest.getProductGroupCode());
            creditMap.putAll(batchQueryCompanyCreditList(Lists.newArrayList(companyCreditQueryRequest)));
        }
        return creditMap;
    }

    /**
     * 查询分子公司信贷
     */
    private Map<String, Long> batchQueryCompanyCreditList(List<CreditQueryRequest> creditQueryRequestList) {
        if (CollectionUtils.isEmpty(creditQueryRequestList)) {
            return Maps.newHashMap();
        }

        //去重同条件信贷查询
        List<CreditQueryRequest> distinctList = creditQueryRequestList.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() ->
                                new TreeSet<>(Comparator.comparing(o -> o.getCustomerCode() + "-"
                                        + o.getChannelCode() + "-"
                                        + o.getOrganizationCode() + "-"
                                        + o.getItemGroupCode()))
                        ), ArrayList::new));
        BatchQueryCreditListRequest request = new BatchQueryCreditListRequest();
        request.setRequestList(distinctList);
        log.info("OrderUpdateBizAssembleOfCustomerCenter#batchQueryCompanyCreditList request: {}", JSON.toJSONString(request));
        Result<List<CreditInfoSDO>> result = creditQueryService.batchQueryCreditList(request);
        log.info("OrderUpdateBizAssembleOfCustomerCenter#batchQueryCompanyCreditList result: {}", JSON.toJSONString(result));
        if (Objects.isNull(result) || CollectionUtils.isEmpty(result.getResult())) {
            return Maps.newHashMap();
        }

        Map<String, Long> creditMap = Maps.newHashMap();
        for (CreditInfoSDO creditInfoSDO : result.getResult()) {
            if (Objects.isNull(creditInfoSDO.getBalance())) {
                continue;
            }
            String creditKey = String.format("%s-%s-%s-%s",
                    creditInfoSDO.getOrganizationCode(),
                    creditInfoSDO.getCustomerCode(),
                    creditInfoSDO.getChannelCode(),
                    creditInfoSDO.getItemGroupCode());
            long balance = new BigDecimal(creditInfoSDO.getBalance()).multiply(new BigDecimal(100)).longValue();
            creditMap.put(creditKey, balance);
        }
        return creditMap;
    }

    /**
     * 查询集团信贷
     */
    private Map<String, Long> batchQueryGroupCreditList(List<QueryCreditRequest> creditQueryRequestList) {
        if (CollectionUtils.isEmpty(creditQueryRequestList)) {
            return Maps.newHashMap();
        }

        //去重同条件信贷查询
        List<QueryCreditRequest> distinctList = creditQueryRequestList.stream().collect(
                Collectors.collectingAndThen(Collectors.toCollection(() ->
                        new TreeSet<>(Comparator.comparing(o ->
                                String.format("%s-%s-%s-%s",
                                        o.getSalesOrganizationCode(),
                                        o.getSoldToPartyCode(),
                                        o.getDistributionChannelCode(),
                                        o.getBusinessType())))), ArrayList::new));

        QueryGroupCreditRequest request = new QueryGroupCreditRequest();
        request.setData(distinctList);
        log.info("OrderUpdateBizAssembleOfCustomerCenter#batchQueryGroupCreditList request: {}", JSON.toJSONString(request));
        Result<QueryCreditResponse> result = mnOrderCenterService.queryGroupCredit(request);
        log.info("OrderUpdateBizAssembleOfCustomerCenter#batchQueryGroupCreditList result: {}", JSON.toJSONString(result));
        if (Objects.isNull(result) || Objects.isNull(result.getResult()) || CollectionUtils.isEmpty(result.getResult().getData())) {
            return Maps.newHashMap();
        }

        Map<String, Long> creditMap = Maps.newHashMap();
        for (SapCreditSDO sapCreditSDO : result.getResult().getData()) {
            if (Objects.isNull(sapCreditSDO.getOBLIG())) {
                continue;
            }
            try {
                String creditKey = String.format("%s-%s-%s-%s",
                        sapCreditSDO.getVKORG(), // 销售组织
                        sapCreditSDO.getKUNNR(), // 客户售达方
                        sapCreditSDO.getVTWEG(), // 分销渠道
                        sapCreditSDO.getSPART()); // 产品组
                long balance = new BigDecimal(sapCreditSDO.getDMBTR().replace(" ", ""))
                        .multiply(new BigDecimal(100)).longValue();
                creditMap.put(creditKey, balance);
            } catch (Exception e) {
                log.error("OrderUpdateBizAssembleOfCustomerCenter#batchQueryGroupCreditList error", e);
            }
        }
        return creditMap;
    }

    /**
     * B信贷余额是否充足
     */
    private boolean isGroupCreditMoneyEnough(OrderBizUpdateRequest updateRequest, Map<String, Long> creditInfoMap) {
        Long mainOrderSum = getTotalAmount(updateRequest);

        String creditKey = String.format("%s-%s-%s-%s",
                updateRequest.getGroupSalesOrganizationCode(),
                updateRequest.getGroupCustomerCode(),
                "20",
                updateRequest.getProductGroupCode());
        Long balance = creditInfoMap.get(creditKey);
        log.info("信贷校验 B mainOrderSum={}, balance={}", mainOrderSum, balance);
        // 强校验信贷，查询不到或者不够的情况下直接返回false
        if (Objects.isNull(balance) || balance < mainOrderSum) {
            return false;
        }
        balance = balance - mainOrderSum;
        creditInfoMap.put(creditKey, balance);
        return true;
    }

    /**
     * 信贷余额是否充足
     */
    private boolean isCreditMoneyEnough(OrderBizUpdateRequest updateRequest, Map<String, Long> creditInfoMap) {
        Long mainOrderSum = getTotalAmount(updateRequest);

        String creditKey = String.format("%s-%s-%s-%s",
                updateRequest.getSalesOrganizationCode(),
                updateRequest.getCustomerCode(),
                updateRequest.getBusinessChannel(),
                updateRequest.getProductGroupCode());
        Long balance = creditInfoMap.get(creditKey);
        log.info("信贷校验 b mainOrderSum={}, balance={}", mainOrderSum, balance);
        // 强校验信贷，查询不到或者不够的情况下直接返回false
        if (Objects.isNull(balance) || balance < mainOrderSum) {
            return false;
        }
        balance = balance - mainOrderSum;
        creditInfoMap.put(creditKey, balance);
        return true;
    }

    private long getTotalAmount(OrderBizUpdateRequest updateRequest) {
        return Optional.ofNullable(updateRequest.getOrderDetails()).orElse(Lists.newArrayList()).stream()
                .map(p -> {
                    if (isNumber(p.getActivityTotalAmount())) {
                        return Long.valueOf(p.getActivityTotalAmount());
                    }
                    if (!isNumber(p.getUnitPrice()) || !isNumber(p.getProductQuantity())) {
                        return 0L;
                    }
                    return new BigDecimal(p.getUnitPrice()).multiply(new BigDecimal(p.getProductQuantity())).multiply(new BigDecimal(100)).longValue();
                }).reduce(0L, Long::sum);
    }

    private boolean isNumber(String params) {
        if (StringUtils.isBlank(params)) {
            return false;
        }
        String reg = "^\\d+(\\.\\d{1,})$|(^[1-9]\\d*$)";
        if (!StringUtils.isNumeric(params) && !Pattern.compile(reg).matcher(params).matches()){
            return false;
        }
        return true;
    }

    private Map<String, SalesBizOrgQueryDTO> querySalesOrgByCodeList(List<OrderBizUpdateRequest> updateRequests) {
        List<SalesBizOrgByBuQueryRequest> salesBizOrgByBuQueryRequests = Lists.newArrayList();
        for (OrderBizUpdateRequest orderBizUpdateRequest : updateRequests) {
            // 对于常温业态目前只支持 6000之下的组织查询
            Set<String> currNormalSalesOrgCode = Sets.newHashSet();
            CollectionUtils.addIgnoreNull(currNormalSalesOrgCode, orderBizUpdateRequest.getBusinessUnitCode());
            CollectionUtils.addIgnoreNull(currNormalSalesOrgCode, orderBizUpdateRequest.getSalesOrganizationCode());
            CollectionUtils.addIgnoreNull(currNormalSalesOrgCode, orderBizUpdateRequest.getSalesDepartmentCode());
            CollectionUtils.addIgnoreNull(currNormalSalesOrgCode, orderBizUpdateRequest.getSalesChannelCode());
            for (String tmpNormalSalesOrgCode : currNormalSalesOrgCode) {

                SalesBizOrgByBuQueryRequest buQueryRequest = new SalesBizOrgByBuQueryRequest();
                //buQueryRequest.setBuCode("6000");
                buQueryRequest.setOrgCode(tmpNormalSalesOrgCode);
                //SalesOrderBusinessTypeEnum.NORMAL_TEMPERATURE.getCode().toString();
                buQueryRequest.setBusinessType(orderBizUpdateRequest.getProductGroupCode());

                salesBizOrgByBuQueryRequests.add(buQueryRequest);
            }
        }

        List<SalesBizOrgQueryDTO> salesBizOrgList = salesOrgAbilityAdapter.querySalesOrgByCodeAndBU(salesBizOrgByBuQueryRequests);
        log.info("OrderUpdateBizAssembleOfCustomerCenter_querySalesOrgByCodeList:request{},response{}", JSON.toJSON(salesBizOrgByBuQueryRequests),JSON.toJSON(salesBizOrgList));
        if(CollectionUtils.isEmpty(salesBizOrgList)) {
            return Maps.newHashMap();
        }

        Map<String, SalesBizOrgQueryDTO> resultMap = Maps.newHashMap();
        for (SalesBizOrgQueryDTO p : salesBizOrgList) {
            if(String.valueOf(SalesOrgTypeEnum.SALES_ORG.getCode()).equals(p.getOrgType())) {
                // 针对销售组织特殊处理
                resultMap.put(p.getOrgType() + "_" + p.getOrgCode(), p);
            } else {
                resultMap.put(p.getOrgCode(), p);
            }
        }
        return resultMap;
    }

    private Map<String, ItemGroupAbilityDTO> queryScItemGroupMap() {
        // 查询所有货品组数据
        ItemGroupAbilityRequest listRequest = new ItemGroupAbilityRequest();
        listRequest.setLimit(999);
        List<ItemGroupAbilityDTO> listResponse = itemQueryAdapter.queryScItemGroup(listRequest);
        return listResponse.stream().collect(Collectors.toMap(ItemGroupAbilityDTO::getProductGroupCode, p -> p, (v1, v2) -> v1));
    }
}
